import { useEffect, useState, useRef } from "react";
// import datas from './data';
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import usePostMsg from "./hooks/usePostMsg";
import { getComponentConfig } from "./data";
import "./App.less";

// import
function App() {
  const componentListRef = useRef([]);
  const [componentList, setComponentList] = useState(componentListRef.current);
  const sensorAPIRef = useRef(null);
  const mainRef = useRef();
  const dataRef = useRef({});
  const { sentMeg } = usePostMsg(function (data) {
    if (data.code === "drag") {
      const dom = mainRef.current;
      const minY = dom.offsetTop + document.documentElement.scrollTop + 64;
      const maxY =
        dom.offsetTop + document.documentElement.scrollTop + dom.offsetHeight;
      const minX = dom.offsetLeft - 20;
      const maxX = dom.offsetLeft + dom.offsetWidth + 20;
      //console.log(minY, maxY, minX, maxX);
      if (
        data.data.y >= minY &&
        data.data.y <= maxY &&
        data.data.x >= minX &&
        data.data.x <= maxX
      ) {
        dataRef.current = {
          x: data.data.x - dom.offsetLeft,
          y: data.data.y - minY,
          type: data.code,
        };
      } else {
        dataRef.current = {};
      }
    } else if (data.code === "drop" && dataRef.current.type) {
      const component = getComponentConfig(data.data);
      componentListRef.current = [component, ...componentListRef.current];
      setComponentList(componentListRef.current);
    } else {
    }
  });
  const mainBody = useRef();
  const [item, setItem] = useState({});
  useEffect(() => {
    //  setTimeout(()=>{
    //       let arr = Array.from(componentList);
    //   const [remove] = arr.splice(2, 1);
    //   arr.splice(1, 0, remove);
    //   setComponentList(arr);
    //  }, 2000);
    //  setTimeout(()=>{
    //   setComponentList([...componentList, {...datas[2], id: 999}])
    //  }, 2000);
  }, []);

  const hanlerMainClick = (item) => {
    setItem(item);
    sentMeg({
      code: "form",
      data: item,
    });
  };

  const hanlerMainDel = (item) => {
    let arr = Array.from(componentList);
    // eslint-disable-next-line array-callback-return
    componentList.map((val, index) => {
      if (item.id === val.id) {
        arr.splice(index, 1);
        console.log("arr: ", arr);
        setComponentList(arr);
      }
    });
  };

  const onDragEnd = (result) => {
    const { source, destination } = result;

    if (!destination) {
      return;
    }

    let arr = Array.from(componentList);
    const [remove] = arr.splice(source.index, 1);
    arr.splice(destination.index, 0, remove);
    setComponentList(arr);
  };

  const preDrag = new useRef(null);
  const aaa = () => {
    if (!preDrag.current) {
      const api = sensorAPIRef.current;
      const preDrag1 = api.tryGetLock("draggable_999", function () {
        console.log("forceStop");
      });
      preDrag.current = preDrag1.snapLift();
    }

    preDrag.current.moveUp();
    // preDrag.current.drop()
  };
  return (
    <div className="App">
      <div className="main-box" ref={mainRef}>
        <div className="main-header operate-box" onClick={aaa}>
          自定义活动
        </div>
        <div className="main-body" ref={mainBody}>
          <DragDropContext
            onDragEnd={onDragEnd}
            sensors={[
              (api) => {
                sensorAPIRef.current = api;
              },
            ]}
          >
            <Droppable droppableId="droppable">
              {(provided, snapshot) => (
                <div ref={provided.innerRef} {...provided.droppableProps}>
                  {componentList.map((val, index) => {
                    const Component = val.component;
                    return (
                      <Draggable
                        draggableId={`draggable_${val.id}`}
                        index={index}
                        key={val.id}
                      >
                        {(provided, snapshot) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                          >
                            <div
                              key={val.id}
                              className={
                                "component-box operate-box" +
                                (val.id == item.id ? " active" : "")
                              }
                              onClick={() => hanlerMainClick(val)}
                              style={{ opacity: snapshot.isDragging ? 0.5 : 1 }}
                            >
                              <Component {...val.config} />
                              <div style={val.style}></div>
                              <div className="component-tag">{val.type}</div>
                              {!snapshot.isDragging && (
                                <div
                                  className="component-del"
                                  onClick={() => hanlerMainDel(val)}
                                ></div>
                              )}
                            </div>
                          </div>
                        )}
                      </Draggable>
                    );
                  })}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          </DragDropContext>
        </div>
        <div className="main-bottom"></div>
      </div>
      {/* <div className="">
        <div className>页面设置</div>
      </div> */}
    </div>
  );
}

export default App;
